﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace OrderingPlatform.MvcExtension
{
    /// <summary>
    /// 自定义全局过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class GloalMvcFiters : ActionFilterAttribute
    {
        public string Message { get; set; }

        /// <summary>
        /// 控制器方法执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var fullName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
            if (HttpContext.Current.User != null)
            {
                if (HasCheck(fullName))
                {
                    if (!HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        var u = "";
                        if (filterContext.RequestContext.HttpContext.Request.Url != null)
                        {
                            u = filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri;
                        }
                        filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { area = "", controller = "Account", action = "LogOn", returnUrl = HttpUtility.HtmlDecode(u) }));
                    }
                }
            }
        }

        private static bool HasCheck(string fullName)
        {
            var list = GetList();
            return list.Any(fullName.Contains);
        }

        private static IEnumerable<string> GetList()
        {
            var list = new List<string> { "OrderingPlatform.WebUI.Areas.SystemManage.Controllers" };
            return list;
        }
    }
}
